#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>

/* 
 * 
 */

using namespace std;

#define NUM 5

void* threadRun(void *name)
{
    cout << "我是次线程 " << (char*)name << endl;
    sleep(1);

    delete[] (char*)name;

    pthread_exit((void*)"EXIT");

    // 直接return "EXIT" 也是可以的
    // return (void*)"EXIT";
}

int main()
{
    pthread_t pt[NUM];

    for(int i = 0; i < NUM; i++)
    {
        // 注册新线程的信息
        char *name = new char[64];
        snprintf(name, 64, "thread-%d", i + 1);
        pthread_create(pt + i, NULL, threadRun, name);
    }

    // 等待次线程运行结束
    void *retval = NULL;
    for(int i = 0; i < NUM; i++)
    {
        int ret = pthread_join(pt[i], &retval);
        if(ret != 0)
            cerr << "等待线程 " << pt[i] << " 失败!" << endl;
        cout << "线程 " << pt[i] << " 等待成功，退出信息是 " << (const char*)retval << endl;
    }

    cout << "所有线程都退出了" << endl;

    return 0;
}

